//
//  GuestCarViewController.m
//  Runone
//
//  Created by runone01 on 16/7/28.
//  Copyright © 2016年 runone. All rights reserved.
//

#import "GuestCarViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "Define.h"
#import "RequestGinsengModel.h"
#import "RequestHelper.h"
#import "AppLocalManager.h"
#import "AppDelegate.h"
#import "HistoryRecoverView.h"
#import "UIView+Addition.h"
#import "AllLastestVehicleDynamic.h"
#import "PickerView.h"
#import "CustomAnnotationView.h"
#import "ROPointAnnotation.h"
#import "VehicleDetailViewController.h"
#import "DropDownBackView.h"
#import "TableOperation.h"
#import "PileInfo.h"
#import "FMDBOperation.h"
#import "TwoPassengersACrisisController.h"
#import "CarListModel.h"
#import "MJExtension.h"
#import "HistoryInquryViewController.h"
#import "ClassifyInquiryController.h"
#import "SVProgressHUD.h"
#import "POPDatePickViewController.h"
#import "RecordViewController.h"
#import "CommonUtilityjudge.h"
#import "OneConst.h"
#import "CarManagerView.h"
#import "HighwayMergeRoadRecordModel.h"
#import "ROInquiryView.h"
#import "Masonry.h"
#import "SRWebSocket.h"
#import "DataCodeModel.h"
#import "GaoJinViewController.h"
#import "TwoCar.h"
#import "TableOperation.h"
#import "UIColor+Addition.h"
#import "RightCodeTool.h"
#import "RequestOutginseng.h"

@interface GuestCarViewController ()<MAMapViewDelegate, UIPopoverPresentationControllerDelegate, UITextFieldDelegate, UIGestureRecognizerDelegate,UITextFieldDelegate,SRWebSocketDelegate,UITabBarControllerDelegate>

@property (nonatomic, strong) NSMutableArray *dataArray;//两客一危数组
@property(nonatomic, strong)SRWebSocket *socket;
@property(nonatomic,strong)NSArray *tempPArray;

@property (nonatomic, strong)MAMapView *mapView;
@property (nonatomic, strong)CarListModel *carListModel;

@property (nonatomic, strong)TwoPassengersACrisisController *CarListVC;//弹出历史记录控制器 请求在这个里面
@property (nonatomic, strong)RecordViewController *record;//弹  出时间控制器

@property (nonatomic, strong)UILabel *dangerousVehiclesLabel;//危险品车辆
@property (nonatomic, strong)UILabel *customerBusLabel;      //两客
@property (nonatomic, strong)UIButton *historyRecordBtn;     //历史记录按钮
@property (nonatomic, strong)UIButton *mapRefreshBtn;        // 刷新地图按钮
@property (nonatomic, strong)UIButton *classifiedInquiryBtn;//分类查询按钮
@property (nonatomic, strong)UIButton *trafficBtn;          //路况

@property (nonatomic, strong)UIButton *DangerousBtn;
@property (nonatomic, strong)DropDownBackView *dropDownBackView;
@property (nonatomic, strong)CarManagerView   *carView;

@property (nonatomic, strong) NSArray *vehicleArray;
@property (nonatomic, strong) ROInquiryView *inquiryView; //分类查询

@property (nonatomic, strong) UIButton *cameraBtn;//摄像枪按钮
@property (assign,nonatomic) CGFloat latitudeDel;
@property (assign,nonatomic) CGFloat longtitudeDel;

@property (strong, nonatomic) UIButton *enlargeBtn;
@property (strong, nonatomic) UIButton *narrowBtn;



@property (nonatomic, strong) NSMutableArray *busArray;    //客车
@property (nonatomic, strong) NSMutableArray *dynamicArray;//危险品车

// ****************************************** -分类查询- ******************************************
@property (nonatomic, strong) NSMutableArray *roadDirectionArray;
@property (nonatomic, copy)   NSString       *defaulRoadTypeStr;//默认的道路类型

// ****************************************** -被查询的道路模型- ******************************************
@property (nonatomic, strong) HighwayMergeRoadRecordModel *beInquiryRoadModel;//被查询的模型
@property (nonatomic, strong) NSMutableArray *filterPileArray;//筛选后的桩号

@property (nonatomic, strong) NSMutableArray *filterTransArray; //过滤车辆类型
@property (nonatomic, strong) NSMutableArray *lastFilterArray;

@property (nonatomic, strong) NSMutableArray *addPointAnnoArray;//添加到地图上的标注的数组
@property (nonatomic, strong) MAPolygon *polygon;

@property (nonatomic, assign) BOOL webSocketIsConnect; //是否开启了webSocket

@property(nonatomic)int selectCount;

@property (nonatomic, copy) NSString *carTypeStr; //选中的车辆类型

@end

@implementation GuestCarViewController

#pragma    - ------两客一危主界面




#pragma mark - lazy load

-(void)getCarNumberDelegate:(NSString *)carNumber {
    HistoryRecoverView *historyVie=[[HistoryRecoverView alloc] init];
    historyVie.vehicleNoField.text=carNumber;
    NSLog(@"%@",historyVie.vehicleNoField.text);
}

//屏幕试配
-(void)defaultAnnimation {
    if (iPhone6plus) {
        MACoordinateSpan  span = MACoordinateSpanMake(2.294286, 1.441601);
        CLLocationCoordinate2D centerCoordinate = CLLocationCoordinate2DMake(24.343247, 113.323544);
        MACoordinateRegion region = MACoordinateRegionMake(centerCoordinate, span);
        _mapView.region = region;
        [_mapView setCenterCoordinate:centerCoordinate animated:NO];
        _mapView.zoomLevel = 9.098923;
        
    }
    if (iPhone6) {
        MACoordinateSpan span = MACoordinateSpanMake(2.246064, 1.386080);
        CLLocationCoordinate2D centerCoordinate = CLLocationCoordinate2DMake(24.343247, 113.323544);
        MACoordinateRegion region = MACoordinateRegionMake(centerCoordinate, span);
        _mapView.region = region;
        [_mapView setCenterCoordinate:centerCoordinate animated:NO];
        _mapView.zoomLevel = 8.964810;
    }
    if (iPhone5) {
        MACoordinateSpan span = MACoordinateSpanMake(2.028609, 1.255746);
        CLLocationCoordinate2D centerCoordinate = CLLocationCoordinate2DMake(24.343247, 113.323544);
        MACoordinateRegion region = MACoordinateRegionMake(centerCoordinate, span);
        _mapView.region = region;
        [_mapView setCenterCoordinate:centerCoordinate animated:NO];
        _mapView.zoomLevel = 8.815084;
    }
}

//实时刷新地图上大头针数据
-(void)getLiangeKeWebSocketDataNotifacation:(NSNotification*)noti
{
    NSDictionary*dic=[noti userInfo];
    NSString*string=[dic objectForKey:@"两客一危"];
    
    [self.mapView removeAnnotations:_addPointAnnoArray];
    [_busArray removeAllObjects];
    [_dynamicArray removeAllObjects];
    
    NSString *str=@"1:";//动态数据
    NSString *str2=@"2:";//离开数据
    
    //离开
    if ([string containsString:str2]) {
        NSString *temp = [string stringByReplacingOccurrencesOfString:str2 withString:@""];
        
        NSMutableArray *arr=[temp mj_JSONObject];
//        DataCodeModel *ReceiveModel=[DataCodeModel mj_objectWithKeyValues:dic];
//        NSArray *arr=[ReceiveModel.DataValue mj_JSONObject];
        for (NSDictionary *dic in arr) {
            AllLastestVehicleDynamic *carModel=[AllLastestVehicleDynamic mj_objectWithKeyValues:dic];
            NSLog(@"%@",carModel.VehicleNo);
            for (int i=0; i<_dataArray.count; i++) {
                AllLastestVehicleDynamic *model=_dataArray[i];
                if ([model.VehicleNo isEqualToString:carModel.VehicleNo]) {
                    [_dataArray removeObject:model];
                    i--;
                }
                
            }
            
        }
    }
    //动态数据
    if ([string containsString:str]) {
        //NSMutableArray *tempArray=[NSMutableArray arrayWithArray:_dataArray];//临时数组
        NSString *temp = [string stringByReplacingOccurrencesOfString:str withString:@""];
//        NSMutableDictionary *dic=[temp mj_JSONObject];
         NSMutableArray *arr=[temp mj_JSONObject];
//        DataCodeModel *ReciveModel=[DataCodeModel mj_objectWithKeyValues:dic];
        
//        NSArray *arr=[ReciveModel.DataValue mj_JSONObject];
        for (NSDictionary *dic in arr) {
            AllLastestVehicleDynamic *carModel=[AllLastestVehicleDynamic mj_objectWithKeyValues:dic];
            NSLog(@"%@",carModel.VehicleNo);
            NSInteger dynamicCount=_dataArray.count;
            BOOL YON=false;
            for (int i=0; i<dynamicCount; i++) {
                AllLastestVehicleDynamic *model=_dataArray[i];
                if ([model.VehicleNo isEqualToString:carModel.VehicleNo]) {
                    [_dataArray removeObject:model];
                    [_dataArray addObject:carModel];
                    dynamicCount--;
                    i--;
                    YON=true;
                }
            }
            if(!YON)
            {
                [_dataArray addObject:carModel];
            }
        }
    }
    
    [self classifyData:_dataArray];//车辆类型
    [self setLabels];//车的数量
    [self loadAnnotationView:_dataArray];//加标注
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _beInquiryRoadModel = [[HighwayMergeRoadRecordModel alloc] init];
    
    _busArray          = [[NSMutableArray alloc] init];
    _dynamicArray      = [[NSMutableArray alloc] init];
    _filterPileArray   = [[NSMutableArray alloc] init];
    _lastFilterArray   = [[NSMutableArray alloc] init];
    _filterTransArray  = [[NSMutableArray alloc] init];
    _addPointAnnoArray = [[NSMutableArray alloc] init];
    _tempPArray        = [[NSArray alloc] init];
    self.tabBarController.delegate=self;
    UILabel *label      = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
    label.text          = @"两客一危";
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor     = [UIColor whiteColor];
    self.navigationItem.titleView = label;
    
    _latitudeDel      = 0.8;
    _longtitudeDel    = 0.9;
    _record=[[RecordViewController alloc] init];
    
    [self loadMapView];
    [self defaultAnnimation];
    [self configUI];
    [self requestData];
    // 监听通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tabBarButtonRepeatClick) name:ROTabBarButtonRepeatClickNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getLiangeKeWebSocketDataNotifacation:) name:@"liangkeyiwei" object:nil];
}

//tabbar图标点击
- (void)tabBarButtonRepeatClick {
    [self selectRefresh];
    [self defaultAnnimation];
//    NSLog(@"点击两次");
}

//刷新数据
-(void)selectRefresh {
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *GetAllLastestVehicleDynamicModel=[[RequestGinsengModel alloc] init];
    GetAllLastestVehicleDynamicModel.URL          = GetAllLastestVehicleDynamicURL;
    GetAllLastestVehicleDynamicModel.DataValue    = @"";
    GetAllLastestVehicleDynamicModel.UpdatedTime  = @"2012-01-12 12:00:00";
    GetAllLastestVehicleDynamicModel.SystemCode   = @"GuangleHighway";
    GetAllLastestVehicleDynamicModel.MethodName   = @"GetAllLastestVehicleDynamic";
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel) {
        if ([requestOutginseng.Code isEqualToString:@"001"]) {
            //[SVProgressHUD showSuccessWithStatus:@"加载完毕"];
        }
        _dataArray = [AllLastestVehicleDynamic mj_objectArrayWithKeyValuesArray:requestOutginseng.DataValue];
        
        [self classifyData:_dataArray];
        [self setLabels];
        [self loadAnnotationView:_dataArray];
    };
    [requestHelper RequestGinsengModel:GetAllLastestVehicleDynamicModel andPushController:self];
}

#pragma mark -添加底部View
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.barTintColor=[UIColor colorWithRed:89 green:187 blue:222];
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden=NO;
    if (!self.socket) {
        AppDelegate*delegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
        
        self.socket=delegate.socket;
        
    }

[self.socket sendString:[NSString stringWithFormat:@"BusDangerous=True"] error:nil];
    [self addCarView];
}

-(void)viewWillDisappear:(BOOL)animated {
//    [self.socket writeString:@"BusDangerous=False"];
//    [self.socket disconnect];
    if (!self.socket) {
        AppDelegate*delegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
        
        self.socket=delegate.socket;
        
    }

    [self.socket sendString:[NSString stringWithFormat:@"BusDangerous=False"] error:nil];
    
    [UIView animateWithDuration:0.35 animations:^{
        self.customerBusLabel.transform       = CGAffineTransformIdentity;
        self.dangerousVehiclesLabel.transform = CGAffineTransformIdentity;
        self.enlargeBtn.transform             = CGAffineTransformIdentity;
        self.narrowBtn.transform              = CGAffineTransformIdentity;
        self.carView.transform                = CGAffineTransformIdentity;
    }];
}
//添加车辆视图
-(void)addCarView {
    _carView=[[CarManagerView alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height, self.view.frame.size.width, BottomSliderViewH)];
    //    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(vehicleManagerDetail)];
    //    [_carView addGestureRecognizer:tap];
    [self.view addSubview:_carView];
}
#pragma mark - 车辆详情暂时屏蔽了
//-(void)vehicleManagerDetail {
//    VehicleDetailViewController *vc      = [[VehicleDetailViewController alloc] init];
//    vc.model                             = _carView.dynamicModel;
//    [self.navigationController pushViewController:vc animated:YES];
//}

//两客一危历史点击
-(void)picker {
    _record.modalPresentationStyle=UIModalPresentationPopover;
    _record.popoverPresentationController.sourceView=self.view;
    _record.popoverPresentationController.sourceRect=CGRectMake(self.view.center.x , self.view.center.y, 0, 0);
    _record.popoverPresentationController.permittedArrowDirections=NO;
    _record.popoverPresentationController.delegate=self;
    [self presentViewController:_record animated:YES completion:nil];
}

#pragma mark - 加载地图
- (void)loadMapView {
    [AMapServices sharedServices].apiKey = GETGAODEPAIKEY;
    _mapView                             = [[MAMapView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds))];
    _mapView.delegate                    = self;
    _mapView.showsCompass                = NO;
    _mapView.showsScale                  = YES;
    _mapView.scaleOrigin                 = CGPointMake(10, self.view.bounds.size.height - 80);
    [self.view addSubview:_mapView];
}

#pragma mark- 请求所有两客一危车辆动态数据
- (void)requestData {
     [SVProgressHUD showWithStatus:@"正在加载中..."];
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *GetAllLastestVehicleDynamicModel=[[RequestGinsengModel alloc] init];
    GetAllLastestVehicleDynamicModel.URL          = GetAllLastestVehicleDynamicURL;
    GetAllLastestVehicleDynamicModel.DataValue    = @"";
    GetAllLastestVehicleDynamicModel.UpdatedTime  = @"2012-01-12 12:00:00";
    GetAllLastestVehicleDynamicModel.SystemCode   = @"GuangleHighway";
    GetAllLastestVehicleDynamicModel.MethodName   = @"GetAllLastestVehicleDynamic";
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel) {
        if (requestOutginseng.DataValue) {
            _dataArray = [AllLastestVehicleDynamic mj_objectArrayWithKeyValuesArray:requestOutginseng.DataValue];
            //        _dataArray     = [[CoordinateConvertTool sharedCoordinateTool] convertVehicleCoorToMapCoor:array];
            [self classifyData:_dataArray];
            [self setLabels];
            [self loadAnnotationView:_dataArray];
            [SVProgressHUD dismiss];
//            [SVProgressHUD showSuccessWithStatus:@"加载成功"];
        }else {
            [SVProgressHUD showErrorWithStatus:@"网络异常"];
        }
    };
    [requestHelper RequestGinsengModel:GetAllLastestVehicleDynamicModel andPushController:self];
}

-(void) classifyData:(NSMutableArray *)arr {
    [_dynamicArray removeAllObjects];
    [_busArray removeAllObjects];
    for (AllLastestVehicleDynamic *model in arr) {
        if ([model.TransType isEqualToString:@"30"] || [model.TransType isEqualToString:@"31"] || [model.TransType isEqualToString:@"32"] ) {
            [_dynamicArray addObject:model];
        }else {
            [_busArray addObject:model];
        }
    }
}

//点击大头针显示的数据
- (void) setLabels {
    //    NSLog(@"运营客车：%lu",(unsigned long)self.busArray.count);
    //    NSLog(@"运营客车：%lu",(unsigned long)self.dynamicArray.count);
    _customerBusLabel.text       = [NSString stringWithFormat:@"营运客车：%lu",(unsigned long)self.busArray.count];
    _dangerousVehiclesLabel.text = [NSString stringWithFormat:@"危化品车辆：%lu",(unsigned long)self.dynamicArray.count];
}

-(void)loadAnnotationView:(NSMutableArray *)array {
    [_mapView removeAnnotations:_addPointAnnoArray];
    [_mapView removeOverlay:_polygon];
    [_addPointAnnoArray removeAllObjects];
    //    _polygon = nil;
    for (int i = 0; i < array.count; i++) {
        AllLastestVehicleDynamic *model    = array[i];
        ROPointAnnotation *pointAnnotation = [[ROPointAnnotation alloc] init];
        pointAnnotation.coordinate         = CLLocationCoordinate2DMake(model.Latitude,model.Longitude );
        pointAnnotation.title              = [NSString stringWithFormat:@"%@",model.VehicleNo];
        //        pointAnnotation.subtitle           = [NSString stringWithFormat:@"%@",model.MCUID];
        pointAnnotation.vehicleModel       = model;
        [_addPointAnnoArray addObject:pointAnnotation];
    }
    NSArray *tempArray=[NSArray arrayWithArray:_addPointAnnoArray];
    [_mapView addAnnotations:tempArray];
}

//刷新数据
-(void)RefreshRequest {
    [self requestData];
}

#pragma mark - 配置UI界面
- (void)configUI {
    //危化品车辆label
    _dangerousVehiclesLabel                 = [[UILabel alloc]initWithFrame:CGRectMake(self.view.bounds.size.width - 130, self.view.bounds.size.height - 84, 130, 30)];
    _dangerousVehiclesLabel.font            = [UIFont systemFontOfSize:12];
    _dangerousVehiclesLabel.textAlignment   = NSTextAlignmentCenter;
    [_dangerousVehiclesLabel setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"dynamic_commercial_btn_bg"]]];
    [self.view addSubview:_dangerousVehiclesLabel];
    //运营客车lebel
    _customerBusLabel                 = [[UILabel alloc]initWithFrame:CGRectMake(self.view.bounds.size.width - 130, self.view.bounds.size.height - 124, 130, 30)];
    _customerBusLabel.font            = [UIFont systemFontOfSize:12];
    _customerBusLabel.textAlignment   = NSTextAlignmentCenter;
    [_customerBusLabel setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"dynamic_commercial_btn_bg"]]];
    [self.view addSubview:_customerBusLabel];
    // 路况_trafficBtn
    _trafficBtn                 = [UIButton buttonWithType:UIButtonTypeCustom];
    _trafficBtn.frame           = CGRectMake(CGRectGetWidth(self.view.bounds) - 15 - PreviewMapBtnWH, 35, PreviewMapBtnWH, PreviewMapBtnWH);
    _trafficBtn.backgroundColor = [UIColor whiteColor];
    [_trafficBtn setBackgroundImage:[UIImage imageNamed:@"traffic_light"] forState:UIControlStateNormal];
    [_trafficBtn setBackgroundImage:[UIImage imageNamed:@"traffic_light_selected"] forState:UIControlStateSelected];
    [_trafficBtn addTarget:self action:@selector(trafficBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_trafficBtn];
    
    //历史记录按钮
    _historyRecordBtn                 = [UIButton buttonWithType:UIButtonTypeCustom];
    _historyRecordBtn.frame           = CGRectMake(CGRectGetWidth(self.view.bounds) - 15 - PreviewMapBtnWH, 35 + PreviewMapBtnWH + 8, PreviewMapBtnWH, PreviewMapBtnWH);
    _historyRecordBtn.backgroundColor = [UIColor whiteColor];
    [_historyRecordBtn setBackgroundImage:[UIImage imageNamed:@"history_record"] forState:UIControlStateNormal];
    [_historyRecordBtn addTarget:self action:@selector(historyRecordBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_historyRecordBtn];
    // 分类查询按钮
    _classifiedInquiryBtn                 = [UIButton buttonWithType:UIButtonTypeCustom];
    _classifiedInquiryBtn.frame           = CGRectMake(CGRectGetWidth(self.view.bounds) - 15 - PreviewMapBtnWH,   35 + PreviewMapBtnWH*2 + 8*2, PreviewMapBtnWH, PreviewMapBtnWH);
    [_classifiedInquiryBtn setBackgroundImage:[UIImage imageNamed:@"category_classify"] forState:UIControlStateNormal];
    [_classifiedInquiryBtn addTarget:self action:@selector(classifiedInquiryBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_classifiedInquiryBtn];
    
    // 告警按钮
    _DangerousBtn                 = [UIButton buttonWithType:UIButtonTypeCustom];
    _DangerousBtn.frame           = CGRectMake(CGRectGetWidth(self.view.bounds) - 15 - PreviewMapBtnWH,  35 + PreviewMapBtnWH * 3 + 8 * 3, PreviewMapBtnWH, PreviewMapBtnWH);
    [_DangerousBtn setBackgroundImage:[UIImage imageNamed:@"alarm_icon"] forState:UIControlStateNormal];
    [_DangerousBtn addTarget:self action:@selector(gaojingVC) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_DangerousBtn];
    
    //刷新按钮
    _mapRefreshBtn                 = [UIButton buttonWithType:UIButtonTypeCustom];
    _mapRefreshBtn.frame           = CGRectMake(CGRectGetWidth(self.view.bounds) - 15 - PreviewMapBtnWH, 35 + PreviewMapBtnWH * 4 + 8 * 4, PreviewMapBtnWH, PreviewMapBtnWH);
    [_mapRefreshBtn setBackgroundImage:[UIImage imageNamed:@"map_refresh_icon"] forState:UIControlStateNormal];
    [_mapRefreshBtn addTarget:self action:@selector(mapRefreshBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_mapRefreshBtn];
    
    // 放大
    _enlargeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_enlargeBtn setBackgroundImage:[UIImage imageNamed:@"zoom_big"] forState:UIControlStateNormal];
    _enlargeBtn.frame  = CGRectMake(self.view.bounds.size.width - 30 - 10, self.view.bounds.size.height - 200, 30, 30);
    [_enlargeBtn addTarget:self action:@selector(enlargeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_enlargeBtn];
    // 缩小
    _narrowBtn  = [UIButton buttonWithType:UIButtonTypeCustom];
    [_narrowBtn setBackgroundImage:[UIImage imageNamed:@"zoom_small"] forState:UIControlStateNormal];
    _narrowBtn.frame  =  CGRectMake(self.view.bounds.size.width - 30 - 10, self.view.bounds.size.height - 170, 30, 30);
    [_narrowBtn addTarget:self action:@selector(narrowBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_narrowBtn];
}

//告警视图点击
- (void) trafficBtnClick:(UIButton *)sender {
    sender.selected=!sender.selected;
    if (sender.selected) {
        _mapView.showTraffic=YES;
    } else {
        _mapView.showTraffic=NO;
    }
}

//告警视图
-(void)gaojingVC {
//    [self.socket writeString:@"BusDangerous=False"];
//    [self.socket disconnect];
    GaoJinViewController *vc=[[GaoJinViewController alloc] init];
    vc.type=1;
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (void)enlargeBtnClick {
    self.latitudeDel   -= 0.1;
    self.longtitudeDel -= 0.1;
    MACoordinateSpan span = MACoordinateSpanMake(self.latitudeDel, self.longtitudeDel);
    CLLocationCoordinate2D centerCoordinate = CLLocationCoordinate2DMake(24.367673, 113.358804);
    MACoordinateRegion region = MACoordinateRegionMake(centerCoordinate, span);
    [_mapView setCenterCoordinate:centerCoordinate animated:NO];
    _mapView.region = region;
}

//历史按钮点击
- (void)narrowBtnClick {
    self.latitudeDel   += 0.1;
    self.longtitudeDel += 0.1;
    MACoordinateSpan span = MACoordinateSpanMake(self.latitudeDel, self.longtitudeDel);
    CLLocationCoordinate2D centerCoordinate = CLLocationCoordinate2DMake(24.367673, 113.358804);
    MACoordinateRegion region = MACoordinateRegionMake(centerCoordinate, span);
    [_mapView setCenterCoordinate:centerCoordinate animated:NO];
    _mapView.region = region;
}

#pragma mark -历史按钮点击
- (void)historyRecordBtnClick {
    if ([[RightCodeTool sharedTool] rightIsEqualTO:@"P0201"]) {
        [self picker];
        __weak __typeof(self)weakSelf = self;
        self.CarListVC=[[TwoPassengersACrisisController alloc] init];
        weakSelf.record.pushBlock=^(NSString *s,NSString *begin,NSString *end){
            weakSelf.CarListVC.carNum = s;
            weakSelf.CarListVC.beginTime = begin;
            weakSelf.CarListVC.endTime  = end;
            weakSelf.CarListVC.carT     = _carTypeStr;
            [weakSelf.navigationController pushViewController:weakSelf.CarListVC animated:YES];
        };
    } else {
        [SVProgressHUD showWithStatus:@"没有该权限"];
    }
}

#pragma mark - 点击刷新按钮
- (void)mapRefreshBtnClick {
    
    [self requestData];
    if (_webSocketIsConnect == NO) {
//        [self.socket connect];
    }
}

- (void) getDataFromDataBase {
    //     [[TableOperation shareInstance] getda];
}


//************************************************** ----—---分类查询Begin-------***********************************************//
#pragma mark - 分类查询
- (void)classifiedInquiryBtnClick {
    //    NSLog(@"查询按钮点击");
    
//    [self.socket disconnect];
    _webSocketIsConnect = NO;
    
    [self getDataFromDataBase];
    
    [self addClassifyInquiryView];
}

- (void) addClassifyInquiryView {
    _inquiryView = [[ROInquiryView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 49)];
    [_inquiryView.confirmBtn addTarget:self action:@selector(inquiryConfirmBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [_inquiryView.canleBtn addTarget:self action:@selector(inquiryViewCancleBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_inquiryView];
}

- (void) inquiryViewCancleBtnClick {
    [_inquiryView removeFromSuperview];
//    [self.socket connect];
    _webSocketIsConnect = YES;
}

#pragma mark - 获取查询的数据
- (void) inquiryConfirmBtnClick {
    [self getRoad]                                                    ;  //获得当前被查询的道路类型
    NSMutableArray *pileArray  = [self filtePile]                     ;  //筛选桩号
    [self drawMutiPoly:pileArray]                                     ;  //画多边形并筛选
    [_inquiryView dimissInquiryView]                                  ;  //关闭查询界面
}

- (void)getRoad {
    AppDelegate *myDelegate = (AppDelegate *)[UIApplication  sharedApplication].delegate;
    for (HighwayMergeRoadRecordModel *roadModel in myDelegate.HighWayRoadArray) {
        if ([_inquiryView.currentRoadModel.RoadUID isEqualToString:roadModel.RoadUID]) {
            _beInquiryRoadModel = roadModel; //获取当前需要被查询的道路模型
            break;
        }
    }
}

- (NSMutableArray *) filtePile {
    AppDelegate *myDelegate = (AppDelegate *)[UIApplication  sharedApplication].delegate;
    NSInteger leftInt   = [_inquiryView.beginPileTF.text integerValue];
    NSInteger rightInt  = [_inquiryView.endPileTF.text integerValue];
    NSMutableArray *filterPileArray = [[NSMutableArray alloc] init];
    NSMutableArray *tempPileArray  = [[NSMutableArray alloc] init];
    for (PileInfo *pileModel in myDelegate.PirArray) {
        if ([pileModel.RoadUID isEqualToString:_beInquiryRoadModel.RoadUID]) { //获取当前道路的模型
            [tempPileArray addObject:pileModel];
        }
    }
//    NSLog(@"%@-%@",_inquiryView.beginPileTF.text,_inquiryView.endPileTF.text);
    
    if (leftInt == 0 && rightInt == 0) {
        leftInt  = 0 ;
        rightInt = tempPileArray.count ;
    } else if (leftInt==0 && rightInt >= tempPileArray.count) {
        leftInt = 0;
        rightInt = tempPileArray.count;
    } else if (leftInt == 0 && rightInt < tempPileArray.count) {
        leftInt =0;
    } else if (leftInt < tempPileArray.count && rightInt == 0) {
        rightInt = tempPileArray.count;
    } else if (leftInt >= tempPileArray.count && rightInt ==0) {
        rightInt = 0 ;
        leftInt  = tempPileArray.count;
    } else if ((leftInt >= 0) && (leftInt <= tempPileArray.count) && (rightInt >= 0) && (rightInt <= tempPileArray.count)){
        if (leftInt > rightInt) {
            leftInt  = leftInt ^ rightInt;
            rightInt = rightInt ^ leftInt;
            leftInt  = leftInt ^ rightInt;
        }
    }else if (leftInt >= tempPileArray.count && rightInt >= tempPileArray.count) {
        leftInt  = 0 ;
        rightInt = tempPileArray.count;
    }else if (leftInt < tempPileArray.count && rightInt >= tempPileArray.count) {
        rightInt = tempPileArray.count;
    }else if (leftInt > tempPileArray.count && rightInt <= tempPileArray.count){
        leftInt = rightInt;
        rightInt = tempPileArray.count;
    }
    
    NSInteger maxInt = rightInt - leftInt;
    [filterPileArray addObjectsFromArray:[tempPileArray subarrayWithRange:NSMakeRange(leftInt, maxInt)]];//过滤后的桩号
    return filterPileArray;
}

- (void) drawMutiPoly:(NSArray *)array{
    NSMutableArray *backArray = [[NSMutableArray alloc] init];
    NSMutableArray *drawArray = [[NSMutableArray alloc] init];
    NSArray *tempArr = [array copy];
    for (int i  = (int)tempArr.count - 1 ; i >=0 ; i--) {
        PileInfo *model = tempArr[i];
        [backArray addObject:model];
    }
    [drawArray addObjectsFromArray:array];
    [drawArray addObjectsFromArray:backArray];
    
    MAMapPoint polyPoints[drawArray.count];
    
    for (int i = 0; i < drawArray.count; i++) {
        PileInfo *model = drawArray[i];
        if (i < array.count) {
            polyPoints[i] = MAMapPointForCoordinate(CLLocationCoordinate2DMake(model.LeftLatitude, model.LeftLongitude));
        }else {
            polyPoints[i] = MAMapPointForCoordinate(CLLocationCoordinate2DMake(model.RightLatitude, model.RightLongitude));
        }
    }
    _polygon = [MAPolygon polygonWithPoints:polyPoints count:drawArray.count];
    [_mapView addOverlay:_polygon];//添加多边形到地图上
    
    NSMutableArray *transArray =  [self filterTransType]; //过滤车辆
    NSArray *lastArray         = [self filterTransDirection:transArray]; //过滤方向
    
    NSMutableArray *filterAllArray = [[NSMutableArray alloc] init];
    for (AllLastestVehicleDynamic *model in lastArray) {
        MAMapPoint point = MAMapPointForCoordinate(CLLocationCoordinate2DMake(model.Latitude, model.Longitude));
        BOOL isContain = MAPolygonContainsPoint(point, polyPoints, drawArray.count);
        if (isContain) {
            [filterAllArray addObject:model];
        }
    }
    
    [_busArray removeAllObjects];
    [_dynamicArray removeAllObjects];
    for (AllLastestVehicleDynamic *model in filterAllArray) {
        if (![model.TransType isEqualToString:@"30"] && ![model.TransType isEqualToString:@"31"] && ![model.TransType isEqualToString:@"32"]) {
            [_busArray addObject:model];
        }else {
            [_dynamicArray addObject:model];
        }
    }
    
    [self setLabels];
    [self loadAnnotationView:filterAllArray];
}
//过滤车辆
- (NSMutableArray *) filterTransType { //过滤车辆
    [_busArray removeAllObjects];
    [_dynamicArray removeAllObjects];
    NSMutableArray *transArray = [[NSMutableArray alloc] init];
    if ([_inquiryView.transTF.text isEqualToString:@"  全部车辆"]) {
        [transArray addObjectsFromArray:_dataArray];
    }
    if ([_inquiryView.transTF.text isEqualToString:@"  营运客车"]) {
        for (AllLastestVehicleDynamic *model in _dataArray) {
            if (![model.TransType isEqualToString:@"30"] && ![model.TransType isEqualToString:@"31"] && ![model.TransType isEqualToString:@"32"]) {
                [transArray addObject:model];
            }
        }
    }
    if ([_inquiryView.transTF.text isEqualToString:@"  危化品车"]) {
        for (AllLastestVehicleDynamic *model in _dataArray) {
            if ([model.TransType isEqualToString:@"30"] || [model.TransType isEqualToString:@"31"] || [model.TransType isEqualToString:@"32"]) {
                [transArray addObject:model];
            }
        }
    }
    for (AllLastestVehicleDynamic *model in transArray) {
        if (![model.TransType isEqualToString:@"30"] && ![model.TransType isEqualToString:@"31"] && ![model.TransType isEqualToString:@"32"]) {
            [_busArray addObject:model];
        }else {
            [_dynamicArray addObject:model];
        }
    }
    [self setLabels];
    return transArray;
}

- (NSMutableArray *) filterTransDirection:(NSMutableArray *)array {
    NSMutableArray *lastArray = [[NSMutableArray alloc] init];
    if ([_inquiryView.directionNum integerValue] == 3) {
        [lastArray addObjectsFromArray:array];
    }else {
        for (AllLastestVehicleDynamic *vehicleModel in array) {
            if ([vehicleModel.Direction integerValue] == [_inquiryView.directionNum integerValue] ) {
                [lastArray addObject:vehicleModel];
            }
        }
    }
    return  lastArray;
}

//************************************************** ----—---分类查询End-------***********************************************//

#pragma mark -地图代理方法
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation {
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
        static NSString *pointReuseIndentifier = @"pointReuseIndentifier";
        CustomAnnotationView *annotationView = (CustomAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndentifier];
        if (annotationView == nil) {
            annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndentifier];
        }
        annotationView.canShowCallout= NO;       //设置气泡可以弹出，默认为NO
        
        ROPointAnnotation *anno = (ROPointAnnotation *)annotation;
        annotationView.vehicleModel = anno.vehicleModel;
        
        if ([annotationView.vehicleModel.TransType isEqualToString:@"30"] || [annotationView.vehicleModel.TransType isEqualToString:@"31"] || [annotationView.vehicleModel.TransType isEqualToString:@"32"]) {
            annotationView.image = [UIImage imageNamed:@"dynamic_vehilce"];//危化品车图标
        }else {
            annotationView.image = [UIImage imageNamed:@"commercial _vehicle"];// 客车图标
        }
        annotationView.centerOffset = CGPointMake(0, -annotationView.image.size.height / 2);
        return annotationView;
    }
    return nil;
}

#pragma mark - 选中annotaionView时调用
- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view {
    CustomAnnotationView *customView     = (CustomAnnotationView *)view;
    _record.str                = customView.vehicleModel.VehicleNo;
    _record.priNo.text         = customView.vehicleModel.VehicleNo;
    _carTypeStr                = customView.vehicleModel.TransType;
    _carView.dynamicModel       = customView.vehicleModel; //customView.carManModel.VehicleNo
    [_carView setDynamicNum:customView.vehicleModel.VehicleNo carType:customView.vehicleModel.TransType dynamicSpeed:customView.vehicleModel.Locator_Rate dynamicDirection:customView.vehicleModel.Direction];
    [UIView animateWithDuration:0.35 animations:^{
        
        self.enlargeBtn.transform             = CGAffineTransformMakeTranslation(0, -BottomSliderViewH);
        self.narrowBtn.transform              = CGAffineTransformMakeTranslation(0, -BottomSliderViewH);
        self.customerBusLabel.transform       = CGAffineTransformMakeTranslation(0, -BottomSliderViewH);
        self.dangerousVehiclesLabel.transform = CGAffineTransformMakeTranslation(0, -BottomSliderViewH);
        _carView.transform                    = CGAffineTransformMakeTranslation(0, BottomSliderDistance);
    }];
}
#pragma mark - 添加图层的代理方法
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay {
    if ([overlay isKindOfClass:[MAPolygon class]]) {
        MAPolygonRenderer *polygonRenderer = [[MAPolygonRenderer alloc] initWithPolygon:overlay];
        polygonRenderer.lineWidth   = 4.f;
        polygonRenderer.strokeColor = [UIColor redColor];
        polygonRenderer.fillColor   = [UIColor clearColor];
        
        return polygonRenderer;
    }
    return nil;
}

#pragma mark - UIPopviewcontroller
-(UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller {
    return UIModalPresentationNone;
}

- (BOOL)popoverPresentationControllerShouldDismissPopover:(UIPopoverPresentationController *)popoverPresentationControlle{
    return YES;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [UIView animateWithDuration:0.35 animations:^{
        self.customerBusLabel.transform       = CGAffineTransformIdentity;
        self.dangerousVehiclesLabel.transform = CGAffineTransformIdentity;
        self.enlargeBtn.transform             = CGAffineTransformIdentity;
        self.narrowBtn.transform              = CGAffineTransformIdentity;
        self.carView.transform                = CGAffineTransformIdentity;
    }];
}

-(void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    NSLog(@"%f--%f--%f--%f--%f",mapView.region.span.latitudeDelta,mapView.region.span.longitudeDelta,mapView.zoomLevel,mapView.region.center.latitude,mapView.region.center.longitude);
}




@end
